package com.sdhs.paas.internet.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class StringUtils
{
  private static StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
  private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

  public static String getRandomString(int length)
  {
    StringBuffer sb = new StringBuffer();
    Random r = new Random();
    int range = buffer.length();
    for (int i = 0; i < length; i++) {
      sb.append(buffer.charAt(r.nextInt(range)));
    }
    return sb.toString();
  }

  public static String getInitialUpperCase(String str) {
    if ((str != null) && (str.length() > 0)) {
      return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    return str;
  }

  public static String formatFraction(double num, int minFractionDigits, int maxFractionDigits)
  {
    NumberFormat nb = NumberFormat.getInstance();
    nb.setMaximumFractionDigits(maxFractionDigits);
    nb.setMinimumFractionDigits(minFractionDigits);
    nb.setGroupingUsed(false);
    String rate = nb.format(num);
    return rate;
  }

  public static String getBefDateString(int day_i)
  {
    Calendar day = Calendar.getInstance();
    day.add(5, day_i);
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(day.getTime());
  }

  public static int getDateTimeLen()
  {
    return "yyyy-MM-dd HH:mm:ss".length();
  }

  public static String getDateTime()
  {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
  }

  public static String getDate()
  {
    return new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
  }

  public static String getDateByFormat(String dateFormat)
  {
    return new SimpleDateFormat(dateFormat).format(Calendar.getInstance().getTime());
  }

  public static String getTime()
  {
    return new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
  }

  public static long parseLongDate(String str)
  {
    try
    {
      return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str).getTime(); } catch (ParseException e) {
    }
    return 0L;
  }

  public static int getSubTime(String str1, String str2)
  {
    return (int)(parseLongDate(str2) - parseLongDate(str1)) / 60000;
  }

  public static String clearNull(String input)
  {
    return isEmpty(input) ? "" : input;
  }

  public static String toChi(String input)
  {
    try
    {
      byte[] bytes = input.getBytes(" ISO8859-1 ");
      return new String(bytes, " GBK ");
    } catch (Exception localException) {
    }
    return input;
  }

  public static String toISO(String input)
  {
    return changeEncoding(input, " GBK ", " ISO8859-1 ");
  }

  public static String changeEncoding(String input, String sourceEncoding, String targetEncoding)
  {
    if ((input == null) || (input.equals(""))) {
      return input;
    }
    try
    {
      byte[] bytes = input.getBytes(sourceEncoding);
      return new String(bytes, targetEncoding);
    } catch (Exception localException) {
    }
    return input;
  }

  public static String encode(String value)
  {
    if (isEmpty(value)) {
      return "";
    }
    try
    {
      value = URLEncoder.encode(value, " GB2312 ");
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return value;
  }

  public static String decode(String value)
  {
    if (isEmpty(value)) {
      return "";
    }
    try
    {
      return URLDecoder.decode(value, " GB2312 ");
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return value;
  }

  public static boolean isNotEmptyMap(Map<?, ?> input)
  {
    return (input != null) && (input.size() > 0);
  }

  public static boolean isNotEmptyList(List<?> input)
  {
    return (input != null) && (input.size() > 0);
  }

  public static boolean isNotEmptyArray(String[] input)
  {
    return (input != null) && (input.length > 0);
  }

  public static boolean isNotEmptyObject(Object obj)
  {
    return (obj != null) && (isNotEmpty(obj.toString()));
  }

  public static boolean isEmpty(String input)
  {
    return (input == null) || (input.length() == 0);
  }

  public static boolean isEmptyArr(String[] input)
  {
    return (input == null) || (input.length == 0);
  }

  public static boolean isNotEmpty(String input)
  {
    return !isEmpty(input);
  }

  public static int parseInt(String str)
  {
    if (isNotEmpty(str)) {
      return Integer.parseInt(str);
    }
    return 0;
  }

  public static int getBytesLength(String input)
  {
    if (input == null) {
      return 0;
    }
    int bytesLength = input.getBytes().length;
    return bytesLength;
  }

  public static void deleteFile(ServletContext application, String filePath)
  {
    if (!isEmpty(filePath)) {
      String physicalFilePath = application.getRealPath(filePath);
      if (!isEmpty(physicalFilePath)) {
        File file = new File(physicalFilePath);
        file.delete();
      }
    }
  }

  public static boolean createFile(ServletContext application, String filePath)
  {
    if (!isEmpty(filePath)) {
      String physicalFilePath = application.getRealPath(filePath);
      if (!isEmpty(physicalFilePath)) {
        File file = new File(physicalFilePath);
        try
        {
          return file.createNewFile();
        } catch (IOException e) {
          System.err.println(" Unable to create file  " + filePath);
        }
      }
    }

    return false;
  }

  public static boolean createDir(ServletContext application, String filePath)
  {
    if (!isEmpty(filePath)) {
      String physicalFilePath = application.getRealPath(filePath);
      if (!isEmpty(physicalFilePath)) {
        try
        {
          File dir = new File(application
            .getRealPath(filePath));
          return dir.mkdirs();
        } catch (Exception e) {
          System.err
            .println(" Unable to create directory  " + filePath);
        }
      }
    }

    return false;
  }

  public static boolean checkFileExists(ServletContext application, String filePath)
  {
    if (!isEmpty(filePath)) {
      String physicalFilePath = application.getRealPath(filePath);
      if (!isEmpty(physicalFilePath)) {
        File file = new File(physicalFilePath);
        return file.exists();
      }
    }

    return false;
  }

  public static String dateToChineseString(Date date)
  {
    if (date == null) {
      return "";
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat(
      " yyyy年MM月dd日 HH:mm:ss ");

    return dateFormat.format(date);
  }

  public static String dateTo14String(Date date)
  {
    if (date == null) {
      return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat(
      " yyyyMMddHHmmss ");

    return dateFormat.format(date);
  }

  public static Date string14ToDate(String input)
  {
    if (isEmpty(input)) {
      return null;
    }

    if (input.length() != 14) {
      return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat(
      " yyyyMMddHHmmss ");
    try
    {
      return dateFormat.parse(input);
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }

  public static boolean getBoolean(HttpServletRequest request, String name)
  {
    return Boolean.valueOf(request.getParameter(name)).booleanValue();
  }

  public static String replaceChar(String s, char c, char c1) {
    if (s == null) {
      return "";
    }
    return s.replace(c, c1);
  }

  public static String replaceString(String s, String s1, String s2) {
    if ((s == null) || (s1 == null) || (s2 == null)) {
      return "";
    }
    return s.replaceAll(s1, s2);
  }

  public static String toHtml(String s) {
    s = replaceString(s, " < ", " &#60; ");
    s = replaceString(s, " > ", " &#62; ");
    return s;
  }

  public static String toBR(String s) {
    s = replaceString(s, " \n ", " <br>\n ");
    s = replaceString(s, " \t ", " &nbsp;&nbsp;&nbsp;&nbsp; ");
    s = replaceString(s, "    ", " &nbsp;&nbsp; ");
    return s;
  }

  public static String toSQL(String s) {
    s = replaceString(s, " \r\n ", " \n ");
    return s;
  }

  public static String replaceEnter(String s) throws NullPointerException {
    return s.replaceAll(" \n ", " <br> ");
  }

  public static String replacebr(String s) throws NullPointerException {
    return s.replaceAll(" <br> ", " \n ");
  }

  public static String replaceQuote(String s) throws NullPointerException {
    return s.replaceAll(" ' ", " '' ");
  }

  public static int toInteger(Object str) {
    return Integer.parseInt(str.toString());
  }

  public static String subString(String str, int count)
  {
    if (isEmpty(str)) return null;
    if (str.length() > count) {
      return str.substring(0, count) + "...";
    }
    return str;
  }

  public static String subString1(String str, int count)
  {
    if (isEmpty(str)) return null;
    if (str.length() > count) {
      return str.substring(0, count);
    }
    return str;
  }

  public static String subString2(String str, int count)
  {
    if (isEmpty(str)) return null;
    if (str.length() > count) {
      return str.substring(0, count) + "..";
    }
    return str;
  }

  public static String convertNumber(String str)
  {
    if (isEmpty(str)) return "0"; try
    {
      if (str.matches("^[0-9]*$")) return str;
      return new DecimalFormat("0.0").format(Double.parseDouble(str));
    } catch (Exception ex) {
      ex.printStackTrace();
    }return "0";
  }

  public static boolean isNumeric(String str)
  {
    int i = str.length();
    do { if (!Character.isDigit(str.charAt(i)))
        return false;
      i--; } while (i >= 0);

    return true;
  }

  public static boolean isLetter(String str)
  {
    if (isEmpty(str)) return false;
    if (str.replaceAll("\\s*", "").matches("^[a-zA-Z]*")) return true;
    return false;
  }

  public static Integer listLen(List<?> list)
  {
    if (isNotEmptyList(list)) return Integer.valueOf(list.size());
    return Integer.valueOf(0);
  }

  public static Integer mapLen(Map<?, ?> map)
  {
    if (isNotEmptyMap(map)) return Integer.valueOf(map.size());
    return Integer.valueOf(0);
  }

  public static String objectToJson(Object obj)
  {
    if (obj == null) return null; try
    {
      return JsonUtils.convertToString(obj);
    } catch (IOException e) {
      e.printStackTrace();
    }return null;
  }

  public static boolean isExist(String str1, String str2)
  {
    boolean b = false;
    if (str2.indexOf("\"" + str1 + "\"") > -1) {
      b = true;
    }
    return b;
  }

  public static boolean isExists(String str1, String str2)
  {
    boolean b = false;
    try {
      if ((isNotEmpty(str1)) && (isNotEmpty(str2)) && 
        (str2.indexOf(str1) > -1))
        b = true;
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    return b;
  }

  public static boolean isExistsArray(String str, List list)
  {
    try
    {
      if ((isNotEmptyList(list)) && (isNotEmpty(str)))
        return list.contains(str);
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }

  public static String convertFnTag(String str)
  {
    if (isNotEmpty(str)) {
      if (str.contains("${fn:getLink('"))
        return getSplicStr(str, "\\$\\{fn\\:getLink\\(\\'", "')}");
      if (str.contains("${fn:getLink(")) {
        return getSplicStr(str, "\\$\\{fn\\:getLink\\(", ")}");
      }
      return null;
    }

    return null;
  }

  private static String getSplicStr(String str, String start, String end)
  {
    StringBuffer sb = new StringBuffer();
    if (isNotEmpty(str)) {
      String[] s = str.split(start);
      for (int i = 0; i < s.length; i++) {
        String temp = s[i];
        if (temp.contains(end)) {
          sb.append(temp.substring(0, temp.lastIndexOf(end)));
        }
      }
    }
    return sb.toString();
  }

  public static String noLastComma(String str)
  {
    if (isNotEmpty(str)) {
      if ((str.endsWith(",")) || (str.endsWith("，"))) {
        return str.substring(0, str.length() - 1);
      }
      return str;
    }
    return "";
  }

  public static void main(String[] args)
    throws IOException
  {
    List list = new ArrayList();
    list.add("zhanglch");
    String str1 = "{\"name\":\"zhanglch\",\"id\":\"1\"}";
    Object obj = JsonUtils.readToObject(str1, HashMap.class);

    String str = "zhanglch";

    System.out.println(list.contains(str));
  }
}
